import { util } from '@kit.ArkTS';
import { IllegalArgumentException } from '../Error/error';

export class Charset {
  private readonly charsetName: string
  static UTF_8: Charset = Charset.forName("utf-8")

  private constructor(name: string) {
    this.charsetName = name
  }

  static forName(name: string): Charset {
    // 可以在这里添加字符集有效性验证
    try {
      // 验证字符集名称是否有效
      new util.TextEncoder(name).encodeInto('')
      return new Charset(name)
    } catch (error) {
      throw new IllegalArgumentException(`Unsupported charset: ${name}`)
    }
  }

  toString(): string {
    return this.charsetName
  }

  name(): string {
    return this.charsetName
  }
}
